package com.zhm.springboot.filters;

import com.zhm.springboot.domain.UserInfo;
import com.zhm.springboot.service.UserInfoService;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * Created by haiming.zhuang on 2016/7/13.
 */
public class CommonFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpSession session = request.getSession();
        if(session.getAttribute("currUser")!=null){
            filterChain.doFilter(servletRequest,servletResponse);
        }else{
            Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            String username = "";
            if (principal instanceof UserDetails) {
                username = ((UserDetails)principal).getUsername();
            } else {
                username = principal.toString();
            }
            if(!"".equals(username)){
                UserInfoService userInfoService =
                        (UserInfoService) WebApplicationContextUtils.
                                getRequiredWebApplicationContext(request.getServletContext()).
                                getBean("userInfoService");
                UserInfo uinfo = userInfoService.findByUsername(username);
                session.setAttribute("currUser",uinfo);
            }
            filterChain.doFilter(servletRequest,servletResponse);
        }


    }

    @Override
    public void destroy() {

    }
}
